import axios from 'axios'
import { ElMessage } from 'element-plus'
import store from '@/store'
// 引入对比方法
import { diffTokenTime } from '@/utils/utils'

const request = axios.create({
  // baseURL: process.env.VUE_APP_BASE_API,
  baseURL: 'http://127.0.0.1:8888/api/private/v1/',
  timeout: 5000
})

// 请求拦截器
request.interceptors.request.use((config) => {
  // 判断登录是否已经过期
  if (localStorage.getItem('token')) {
    if (diffTokenTime()) {
      store.dispatch('user/loginOut')
      return Promise.reject(new Error('token失效'))
    }
  }
  config.headers.Authorization = localStorage.getItem('token')
  return config
}, (error) => {
  return new Promise(new Error(error))
})

// 响应拦截器
request.interceptors.response.use(
  (res) => {
    const { data, meta } = res.data
    if (meta.status === 200 || meta.status === 201) {
      // ElMessage({
      //   message: '登录成功',
      //   type: 'success'
      // })
      return data
    } else {
      ElMessage.error(meta.msg)
      return Promise.reject(new Error(meta.msg))
    }
  }, (error) => {
    error.res && ElMessage.error(error.response.data)
    return Promise.reject(new Error(error.response.data))
  })
export default request
